package service

import (
	"errors"
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"github.com/jinzhu/gorm"
	"go-im-server-demo/src/model"
	"go-im-server-demo/src/utils"
	jwtu "go-im-server-demo/src/utils/jwt"
	"strconv"
	"time"
)

var mh *utils.MailHelper

func init() {
	mh = utils.NewMailHelper(
		"smtp.qq.com",
		25,
		"1162280694@qq.com",
		"nxbtexihtgqfbaga",
	)
}

func SendEmail(email string, vcode string) error {
	return mh.SendMail("IM", email, "邮箱验证码", "<h5>邮箱验证码:</h5><h2><span style='color:green'>"+vcode+"</span></h2>", true)
}

func Login(email string) (string, error) {

	db := model.GetDB()
	// 查询邮箱地址是否存在与表中
	var u model.User2
	tx := db.Begin()

	dbs := tx.Where("email = ?", email).First(&u)
	if gorm.IsRecordNotFoundError(dbs.Error) {

		t := time.Now()

		u = model.User2{
			Email:     email,
			CreatedAt: t,
			UpdateAt:  &t,
		}
		tx.Create(&u)
	}

	var uid uint = u.ID

	jwtu := jwtu.Default()
	ts, err := jwtu.Sign(jwt.MapClaims{
		"uid": strconv.Itoa(int(uid)),
	}, time.Hour*24*7)
	if err != nil {
		fmt.Println(err)
		return "", err
	}

	fmt.Println(ts)

	tx.Commit()
	return ts, nil
}

func GetUserInfo(uid string) (*model.User2, error) {
	var u model.User2

	db := model.GetDB()
	uidInt, _ := strconv.Atoi(uid)
	dbs := db.First(&u, uint(uidInt))
	if dbs.Error != nil {
		fmt.Println(dbs.Error)
		return nil, dbs.Error
	}
	if dbs.RowsAffected == 0 {
		return nil, errors.New("查询的数据不存在")
	}
	return &u, nil
}

func SetUserName(uid, name string) error {
	uidInt, _ := strconv.Atoi(uid)
	db := model.GetDB()

	err := db.Model(&model.User2{}).Where("id = ?", uidInt).Update("name", name).Error
	if err != nil {
		return err
	}
	return nil
}
